<?php

namespace App\Http\Controllers;

use App\Models\BorrowRecord;
use App\Models\Fine;
use App\User;
use Exception;
use Illuminate\Database\QueryException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\SmsSendConn;
use Tymon\JWTAuth\Facades\JWTAuth;

class UserController extends Controller
{
    public function personalInformation()
    {
        $user=JWTAuth::parseToken()->authenticate();
        $user->group=$user->gid==0?"普通用户":"管理员用户";
        unset($user->gid);
        unset($user->borrow_num);
        unset($user->id);
        return $this->success($user);
    }

    public function borrowRecord()
    {
        $user=JWTAuth::parseToken()->authenticate();
        $uid =$user->id;
        $records=BorrowRecord::where('uid',$uid)->leftJoin('books as b','b.bid','borrow_records.bid')
            ->select('borrow_id','b.name','borrow_records.state','b.publisher','b.author','b.bid','borrow_records.created_at','borrow_records.timescale')
            ->orderBy('borrow_records.created_at')
            ->get();
        return $this->success($records);
    }

    public function changeStateOfCommonUser(Request $request)
    {
        $validate=Validator::make($request->all(),[
            'uid'=>'required|exists:users,id',
            'state'=>'required|in:0,2'
        ]);

        if($validate->fails())
        {
            $error=$validate->errors();
            return $this->fail(400006,$error);
        }

        $uid=$request->get('uid');
        $state=$request->get('state');

        try
        {
            User::where('id',$uid)->update([
                'state'=>$state
            ]);
        }
        catch (QueryException $e)
        {
            return $this->fail(500001);
        }

        return $this->success();
    }

    public function userList()
    {
        try
        {
            $users=User::where('gid','0')->select('id','real_name','borrow_id','state')->get();
            foreach ($users as $user)
            {
                $over_timescale_times=BorrowRecord::where('uid',$user->id)
                    ->where(function ($query){
                      $query->where('state',2)->orWhere('state',1);
                    })
                    ->count();

                $not_pay_fine_times=BorrowRecord::where('uid',$user->id)
                    ->where('state',2)->count();

                $borrow_times=BorrowRecord::where('uid',$user->id)->count();
                $user->over_timescale_times=$over_timescale_times;
                $user->not_pay_fine_times=$not_pay_fine_times;
                $user->borrow_times=$borrow_times;
            }
        }
        catch (QueryException $e)
        {
            return $this->fail(500002);
        }
        return $this->success($users);
    }

    public function userBorrowedRecord(Request $request)
    {
        $validate=Validator::make($request->all(),[
            'uid'=>'exists:users,id|required_without:borrow_id|exists:users,id',
            'borrow_id'=>'exists:users,borrow_id|required_without:uid|exists:users,borrow_id'
        ]);

        if($validate->fails())
        {
            $error=$validate->errors();
            return $this->fail(400006,$error);
        }

        $uid=$request->get('uid');
        $borrow_id=$request->get('borrow_id');
        $res=BorrowRecord::leftJoin('users as u','u.id','borrow_records.uid')
            ->leftJoin('books as b','b.bid','borrow_records.bid')
            ->leftJoin('fines as f','f.borrow_id','borrow_records.borrow_id')
            ->where('borrow_records.state','<',2)
            ->where(function ($query) use ($uid,$borrow_id){
                $query->where('u.id',$uid)->orWhere('u.borrow_id',$borrow_id);
            })
            ->select('borrow_records.borrow_id','borrow_records.state','b.name','borrow_records.created_at','borrow_records.timescale')
            ->get();


        foreach ($res as $r)
        {
            $fines=Fine::where('borrow_id',$r->borrow_id)->get();
            if($fines->isNotEmpty())
            {
              $r->fine=$fines[0]->price;
            }
            else
            {
              $r->fine=0;
            }
        }

        return $this->success($res);

    }

    public function pusher()
    {
//
//        $url = 'http://api01.monyun.cn:7901/sms/v2/std/';
////北方短信节点url地址
////$url = 'http://api02.monyun.cn:7901/sms/v2/std/';
//        $smsSendConn = new SmsSendConn($url);
//        $data=array();
////设置账号(必填)
//        $data['userid']='E105VN';
////设置密码（必填.填写明文密码,如:1234567890）
//        $data['pwd']='86aDoI';
/////////////////////////////////////////////////////////////////////////////////////
//
//        /*
//        * 单条发送 接口调用
//        */
//// 设置手机号码 此处只能设置一个手机号码(必填)
//        $data['mobile']='13672092237';
////设置发送短信内容(必填)
//        $data['content']='验证码：6666，打死都不要告诉别人哦！';
//// 业务类型(可选)
//        $data['svrtype']='';
//// 设置扩展号(可选)
//        $data['exno']='';
////用户自定义流水编号(可选)
//        $data['custid']='';
//// 自定义扩展数据(可选)
//        $data['exdata']='';
//        try {
//            $result = $smsSendConn->singleSend($data);
//            if ($result['result'] === 0) {
//                print_r("单条信息发送成功！");
//            } else {
//                print_r("单条信息发送失败，错误码：" . $result['result']);
//            }
//        }catch (\PHPUnit\Framework\Exception $e) {
//            print_r($e->getMessage());//输出捕获的异常消息，请根据实际情况，添加异常处理代码
//            return false;
//        }
//        return $this->success($result);

        $phone7=BorrowRecord::where('timescale','<',date('Y-m-d H:i:s',strtotime('+7day')))
            ->where('timescale','>',date('Y-m-d H:i:S',time()))
            ->where('borrow_records.state','<',2)
            ->leftJoin('users as u','u.id','borrow_records.uid')
            ->select('u.phone')
            ->distinct()
            ->get();

        foreach ($phone7 as $p)
        {
            if($p->phone==null)
            {
                continue;
            }


            $url = 'http://api01.monyun.cn:7901/sms/v2/std/';
            $smsSendConn = new SmsSendConn($url);
            $data=array();
            $data['userid']='E105VN';
            $data['pwd']='86aDoI';
            $data['mobile']=$p->phone;

            $data['content']='您借阅的图书将于3天后过期，请按时归还！超时罚款 1 元/天';
            try {
                $result = $smsSendConn->singleSend($data);
                if ($result['result'] === 0) {
                    print_r("单条信息发送成功！");
                } else {
                    print_r("单条信息发送失败，错误码：" . $result['result']);
                }
            }catch (\PHPUnit\Framework\Exception $e) {
                print_r($e->getMessage());//输出捕获的异常消息，请根据实际情况，添加异常处理代码
            }
        }

        return $this->success($result);

    }

}